﻿using System;
using System.Collections.Generic;
using System.Linq;
using DMS.BaseClass;
using DMS.Business.Modules.Configuation;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
using DMS.Base;
using DMS.Business.Modules.Organization;
using DMS.Business.BaseClass;

namespace DMS.Business.Utility
{
    /// <summary>
    /// 配置管理
    /// </summary>
    public class ConfigHelper : BaseService
    {
        #region 系统配置参数

        #region SQL查询句子
        /// <summary>
        /// 配置表查询主句
        /// </summary>
        private const string SQL_SYS_Params = @"SELECT {0} [ParamID]
                                                      ,[ParamName]
                                                      ,[ParamType]
                                                      ,[ParamValue]
                                                      ,[IsBuildIn]
                                                      ,[IsDisplay]
                                                  FROM [dbo].[SYS_Params]";
        /// <summary>
        /// 配置表统计主句
        /// </summary>
        private const string SQL_SYS_Params_Count = @"SELECT COUNT(*) AS Total
                                                    FROM [dbo].[SYS_Params]";
        /// <summary>
        /// 配置表排序子句
        /// </summary>
        private const string SQL_SYS_Params_Order = @"ORDER BY [ParamType],[ParamName]";
        /// <summary>
        /// 配置表更新主句
        /// </summary>
        private const string SQL_SYS_Params_Update = @"UPDATE [dbo].[SYS_Params]
                                                           SET [ParamValue] = @ParamValue
                                                         WHERE [ParamID] = @ParamID";
        #endregion

        /// <summary>
        /// 获取系统配置参数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static SysConfig GetSysConfigByID(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException("id", "查询系统参数时，参数标识(ID)不能为空。");
            }

            string condition = string.Empty;
            List<DbParameter> DbParams = new List<DbParameter>();

            condition += " AND [ParamID] = @ParamID";
            DbParameter paramID = DBHelper.CreateParamer();
            paramID.ParameterName = "ParamID";
            paramID.Value = id.ToString();
            DbParams.Add(paramID);

            int total = 0;
            List<SysConfig> configs = GetSysConfigs(-1, 1, out total, condition, DbParams);
            SysConfig config = configs.DefaultIfEmpty(null).FirstOrDefault();

            return config;
        }
        /// <summary>
        /// 获取系统配置参数列表
        /// </summary>
        /// <param name="limite">返回数量限制</param>
        /// <param name="page">页码</param>
        /// <param name="total">总数</param>
        /// <param name="condition">查询字符串</param>
        /// <param name="dbParams">条件参数</param>
        /// <returns></returns>
        public static List<SysConfig> GetSysConfigs(int limite, int page, out int total, string condition, List<DbParameter> dbParams)
        {
            total = 0;
            Database db = DBHelper.Instance;
            string topClause = string.Empty;
            string whereClause = string.Format("WHERE 1 = 1 {0}", condition);
            string countSql = string.Format("{0} {1}", SQL_SYS_Params_Count, whereClause);
            if (limite > 0)
            {
                topClause = string.Format("Top {0}", limite.ToString());

                if (page > 1)
                {
                    int pageCount = (page - 1) * limite;
                    string subClause = string.Format(@"SELECT TOP {0} [ParamID]
                                                       FROM [dbo].[SYS_Params] {1}", pageCount.ToString(), whereClause);
                    whereClause += string.Format("AND [ParamID] NOT IN({0})", subClause);
                }
            }
            string mainClause = string.Format(SQL_SYS_Params, topClause);
            string sql = string.Format("{0} {1} {2}", mainClause, whereClause, SQL_SYS_Params_Order);
            DbCommand command = db.GetSqlStringCommand(sql);
            if (dbParams != null)
            {
                command.Parameters.AddRange(dbParams.ToArray());
            }

            DataSet ds = db.ExecuteDataSet(command);
            List<SysConfig> configs = new List<SysConfig>();
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                total = GetRecordCount(countSql, dbParams);
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string id = dr["ParamID"].ToString();
                    SysConfig config = new SysConfig(id);
                    FillSysConfigInfo(dr, config);

                    configs.Add(config);
                }
            }

            return configs;
        }

        /// <summary>
        /// 有默认配置就取默认配置，没有就取公共配置
        /// </summary>
        /// <param name="configID"></param>
        /// <returns></returns>
        public static string GetConfigParamValue(string configID, string memberID)
        {
            string sql = @"SELECT p.ParamID
                              ,[MemberID]
                              ,[MemberType]
                              ,ISNULL(m.paramvalue, p.paramvalue) paramvalue
                          FROM SYS_Params p
                          left join [SYS_Params_Member] m
                          on p.paramid = m.paramid
                          where p.ParamID = m.ParamID
                          and m.MemberID = @memberId
                          and p.ParamID = @paramId";
            Database db = DBHelper.Instance;
            DbCommand command = db.GetSqlStringCommand(sql);
            command.Parameters.Add(DBHelper.CreateParamer("paramId", configID));
            command.Parameters.Add(DBHelper.CreateParamer("memberId", configID));
            DataSet ds = db.ExecuteDataSet(command);
            return Convert.ToString(ds.Tables[0].Rows[0]["paramvalue"]);
        }

        /// <summary>
        /// 更新配置
        /// </summary>
        /// <param name="config"></param>
        public static void UpdateSysConfig(SysConfig config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config", "更新系统配置时，转入的配置项对象不能为空。");
            }

            Database db = DBHelper.Instance;
            DbCommand cmd = db.GetSqlStringCommand(SQL_SYS_Params_Update);

            DbParameter p_ParamID = cmd.CreateParameter();
            p_ParamID.ParameterName = "ParamID";
            p_ParamID.Value = config.ID;
            cmd.Parameters.Add(p_ParamID);

            DbParameter p_ParamValue = cmd.CreateParameter();
            p_ParamValue.ParameterName = "ParamValue";
            p_ParamValue.Value = config.Value;
            cmd.Parameters.Add(p_ParamValue);

            db.ExecuteNonQuery(cmd);
        }

        private static void FillSysConfigInfo(DataRow dr, SysConfig config)
        {
            // 检查数据行参数
            if (dr == null)
            {
                throw new ArgumentNullException("dr", "填充配置信息时，配置数据行dr不能为空。");
            }
            if (dr["ParamID"] == null || dr["ParamID"].ToString().Trim() == string.Empty)
            {
                throw new ArgumentNullException("ParamID", "填充配置信息时，配置数据行中的ParamID字段为空值，请检查数据。");
            }

            // 检查配置参数
            if (config == null)
            {
                config = new SysConfig(dr["ParamID"].ToString());
            }

            // 装载配置信息
            config.Name = dr["ParamName"].ToString();
            config.Value = dr["ParamValue"].ToString();

            if (dr["ParamType"] != null && dr["ParamType"].ToString() != string.Empty)
            {
                config.Type = (ParamTypes)Enum.Parse(typeof(ParamTypes), dr["ParamType"].ToString());
            }

            config.IsDisplay = dr["IsDisplay"].ToString() == "1";
            config.IsBuildIn = dr["IsBuildIn"].ToString() == "1";
        }
        #endregion

        #region 成员配置参数

        #region SQL查询句子
        /// <summary>
        /// 配置表查询主句
        /// </summary>
        private const string SQL_SYS_Params_Member = @"SELECT {0} [ParamID]
                                                              ,[MemberID]
                                                              ,[MemberType]
                                                              ,[ParamValue]
                                                          FROM [dbo].[SYS_Params_Member]";
        /// <summary>
        /// 配置表统计主句
        /// </summary>
        private const string SQL_SYS_Params_Member_Count = @"SELECT COUNT(*) AS Total
                                                    FROM [dbo].[SYS_Params_Member]";

        private const string SQL_SYS_Params_Member_Add = @"INSERT INTO [dbo].[SYS_Params_Member]
                                                                   ([ParamID]
                                                                   ,[MemberID]
                                                                   ,[MemberType]
                                                                   ,[ParamValue])
                                                             VALUES
                                                                   (@ParamID
                                                                   ,@MemberID
                                                                   ,@MemberType
                                                                   ,@ParamValue)";
        private const string SQL_SYS_Params_Member_Update = @"UPDATE [dbo].[SYS_Params_Member]
                                                                   SET [ParamValue] = @ParamValue";
        private const string SQL_SYS_Params_Member_Delete = @"DELETE FROM [dbo].[SYS_Params_Member]";
        /// <summary>
        /// 配置表排序子句
        /// </summary>
        private const string SQL_SYS_Params_Member_Order = @"";
        #endregion

        public static MemberConfig GetMemberConfig(string memberID, string configID)
        {
            List<MemberConfig> memberConfigs = ConfigHelper.GetMemberConfigs(memberID);
            MemberConfig config = (from c in memberConfigs
                                   where c.ID.ToUpper() == configID.ToUpper()
                                   select c).ToList().DefaultIfEmpty(null).FirstOrDefault();

            return config;
        }
        public static List<MemberConfig> GetMemberConfigs(string memberID)
        {
            List<MemberConfig> configs = new List<MemberConfig>();

            string condition = string.Format(" AND [MemberID] = '{0}'", memberID.ToString().ToUpper());

            string mainClause = string.Format(SQL_SYS_Params_Member, string.Empty);
            string whereClause = string.Format("WHERE 1 = 1 {0}", condition);
            string sql = string.Format("{0} {1} {2}", mainClause, whereClause, SQL_SYS_Params_Member_Order);

            Database db = DBHelper.Instance;
            DbCommand command = db.GetSqlStringCommand(sql);
            DataSet ds = db.ExecuteDataSet(command);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string id = dr["ParamID"].ToString();
                    ActorTypes memberType = (ActorTypes)Enum.Parse(typeof(ActorTypes), dr["MemberType"].ToString());
                    SysConfig defaultConfig = GetSysConfigByID(id);

                    MemberConfig config = new MemberConfig(memberID, memberType, defaultConfig);
                    config.Value = dr["ParamValue"].ToString();

                    configs.Add(config);
                }
            }

            return configs;
        }

        public static void AddMemberConfig(SysConfig config, string value, string memberID, ActorTypes memberType)
        {
            Database db = DBHelper.Instance;
            DbCommand cmd = db.GetSqlStringCommand(SQL_SYS_Params_Member_Add);

            DbParameter p_ParamID = cmd.CreateParameter();
            p_ParamID.ParameterName = "@ParamID";
            p_ParamID.Value = config.ID;
            cmd.Parameters.Add(p_ParamID);

            DbParameter p_MemberID = cmd.CreateParameter();
            p_MemberID.ParameterName = "@MemberID";
            p_MemberID.Value = memberID.ToString().ToUpper();
            cmd.Parameters.Add(p_MemberID);

            DbParameter p_MemberType = cmd.CreateParameter();
            p_MemberType.ParameterName = "@MemberType";
            p_MemberType.Value = (int)memberType;
            cmd.Parameters.Add(p_MemberType);

            DbParameter p_ParamValue = cmd.CreateParameter();
            p_ParamValue.ParameterName = "@ParamValue";
            p_ParamValue.Value = value;
            cmd.Parameters.Add(p_ParamValue);

            db.ExecuteNonQuery(cmd);
        }
        public static void UpdateMemberConfig(MemberConfig config)
        {
            string condition = "WHERE [ParamID] = @ParamID AND [MemberID] = @MemberID";
            string sql = string.Format("{0} {1}", SQL_SYS_Params_Member_Update, condition);
            Database db = DBHelper.Instance;
            DbCommand cmd = db.GetSqlStringCommand(sql);

            DbParameter p_ParamID = cmd.CreateParameter();
            p_ParamID.ParameterName = "@ParamID";
            p_ParamID.Value = config.ID;
            cmd.Parameters.Add(p_ParamID);

            DbParameter p_MemberID = cmd.CreateParameter();
            p_MemberID.ParameterName = "@MemberID";
            p_MemberID.Value = config.MemberID;
            cmd.Parameters.Add(p_MemberID);

            DbParameter p_ParamValue = cmd.CreateParameter();
            p_ParamValue.ParameterName = "@ParamValue";
            p_ParamValue.Value = config.Value;
            cmd.Parameters.Add(p_ParamValue);

            db.ExecuteNonQuery(cmd);
        }
        public static void DeleteMemberConfig(MemberConfig config)
        {
            string id = config.ID;
            string memberID = config.MemberID;

            string condition = string.Format(" AND [ParamID] = '{0}'", id);
            condition += string.Format(" AND [MemberID] = '{0}'", memberID);

            string sql = string.Format("{0} WHERE 1 = 1 {1}", SQL_SYS_Params_Member_Delete, condition);
            Database db = DBHelper.Instance;
            DbCommand cmd = db.GetSqlStringCommand(sql);
            db.ExecuteNonQuery(cmd);
        }
        #endregion
    }
}
